//待购对象，购物车内的商品
//购物车没有getCash这种计算商品总价的方法，而是通过Ach订单对象模拟生成订单来计算价格
(function() {
	var db = require("../db/index");
	var config = require("../_include/config");
	var db_table_name = config.dbname.userCartGoods;
	var db_id_prefix = config.dbIdPrefix.userCartGoods;
	var helper = require("../_include/helper");

	//构造函数
	var _con = function(info) {
		var self = this;
		//ID编号
		self._id = db_id_prefix + /*"_"+goods_id+"_"+*/ Math.random().toString(16).substr(2) + (+new Date).toString(16);

		self.setGoodsInfo(info.goods_info);

		self.bus_id = info.bus_id;
		// self.recommender_id = info.recommender_id;

		//TODO:这里的可能会有BUFF注入的BUG！！
		//TODO：修复方案，对BUFF进行分类分级，这里只能收抵用类BUFF
		self.buffs = []; //使用哪些抵价优惠BUFF

		self.create_time = (+new Date);

		db.insert(db_table_name, self);
		console.log("将", self.goods_info, "商品放入购物车");
	};
	//PS:模块的暴露放在require skill前面，因为二者互相依赖
	module.exports = _con;
	//技能
	_con.prototype = require("./skill");

	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		if (result) {
			result.__proto__ = _con.prototype;
			// result.getCash();
		}
		return result;
	};
	//判断一个Goods_id是否是自身所指向的goods_id;
	_con.isThisGoods = function(cart_goods_id, goods_id) {
		if (cart_goods_id.indexOf("_" + goods_id + "_") !== -1) {
			return true;
		}
	};
	//合并购物车商品
	_con.concat = function(user_id, cart_id_list) {
		var goods_info = [];
		var user = UserCon.get(user_id);
		if (!user) {
			throwCusError("找不到指定用户")
		}
		var user_cart = user.cart || [];
		var bus_id;
		cart_id_list.forEach(function(cart_goods_id) {
			if (!cart_goods_id) {
				return
			}
			if (user_cart.indexOf(cart_goods_id) === -1) {
				console.log(cart_goods_id)
				throwCusError("购物车商品不属于指定用户，合并失败")
			}
			var cart_goods = _con.get(cart_goods_id);
			if (bus_id) {
				if (bus_id !== cart_goods.bus_id) {
					throwCusError("购物车内的商品所在的商家不同，合并失败");
				}
			} else {
				bus_id = cart_goods.bus_id
			}
			if (cart_goods) {
				goods_info = goods_info.concat(cart_goods.goods_info);
			} else {
				throwCusError("找不到指定购物车商品")
			}
		});
		//生成新的购物车对象
		var cart_id = user.addGoodsToCart(goods_info, bus_id);
		return cart_id;
	}


	var GoodsCon = require("../goods/_con");
	var UserCon = require("../user/_con");
	var BusCon = require("../bus/_con");
}());